﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using StoreTransport.Business.Helper;
using StoreTransport.DAO;

namespace StoreTransport.Presentation.Forms {
    public partial class UserHistory : Form {
        public UserHistory() {
            InitializeComponent();
        }
        int DefaultReportRange = -1;
        private void UserHistory_Load(object sender, EventArgs e) {
            _btnShowResult.Select();
            _dtpTo.Value = DateTime.Now;
            _dtpFrom.Value = DateTime.Now.AddMonths(DefaultReportRange);
        }

        private void _btnShowResult_Click(object sender, EventArgs e) {
            StoreTransportDataContext context = CommonHelper.GetContext();
            var source = context.ReportHistories.Where(c => c.ReportDate >= _dtpFrom.Value
                                                        && c.ReportDate <= _dtpTo.Value);
            _grdHistoryReport.AutoGenerateColumns = false;
            if (_cbxShowByKind.Checked) {
                _grdHistoryReport.Columns["ProductKindName"].Visible = true;
                _grdHistoryReport.DataSource = source.OrderBy(c => c.ReportDate).ThenBy(c => c.ProductLineName)
                    .Cast<ReportHistory>();
            } else {
                List<ReportHistory> reportByLine = new List<ReportHistory>();
                foreach (var row in source) {
                    var selectedItem = reportByLine.FirstOrDefault(c => c.Description.Equals(row.Description));
                    if (selectedItem == null) {
                        reportByLine.Add(row);
                    } else {
                        //selectedItem.MarketTSNumber += row.MarketTSNumber;
                        selectedItem.StoreTSNumber += row.StoreTSNumber;
                    }
                }
                _grdHistoryReport.Columns["ProductKindName"].Visible = false;
                _grdHistoryReport.DataSource = reportByLine.OrderBy(c => c.ReportDate).ThenBy(c => c.Username).
                    ThenBy(c => c.ProductLineName).Cast<ReportHistory>().ToList();
            }
        }
    }
}
